/**
 * Administrator
 * 2010 2010-3-1 下午04:50:02
 * 
 */
package com.ding.easyme.app.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;

/**
 * @author Administrator
 * 
 */
public class FileUtil {

	/**
	 * 计算文件夹大小
	 */
	public static final long getSize(File dir) {
		long retSize = 0;
		if (dir == null) {
			return retSize;
		}
		if (dir.isFile()) {
			return dir.length();
		}
		File[] entries = dir.listFiles();
		int count = entries.length;
		for (int i = 0; i < count; i++) {
			if (entries[i].isDirectory()) {
				retSize += getSize(entries[i]);
			} else {
				retSize += entries[i].length();
			}
		}
		return retSize;
	}

	/**
	 * 创建文件
	 * 
	 * @param pathName
	 *            路径名
	 * @return void
	 */
	private static void createFile(File file) {
		//File file = new File(pathName);
		if (!file.getParentFile().exists()) {
			//System.out.println("文件所在目录不存在，准备创建...");
			if (file.getParentFile().mkdirs()) {
				System.out.println("目录创建成功，准备创建文件..."+file.getParentFile());
				try {
					if (file.createNewFile()) {
						return;
					} else {
						return;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				return;
			}
		} else {
			try {
				if (file.createNewFile()) {
					return;
				} else {
					return;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
    /**
     * 将字符串写入到文件中
     *
     * @param file
     * @param txt
     * @throws Exception
     */
    public static void stringWriteToFile(File file, String txt) throws Exception { 
    	BufferedReader reader = null;
    	PrintWriter writer = null;
		if (!file.exists()) {
			FileUtil.createFile(file);
		}
		try {
			String s;
			reader = new BufferedReader(new StringReader(txt));
			writer = new PrintWriter(new BufferedWriter(
					new FileWriter(file)));
			while ((s = reader.readLine()) != null)
				writer.println(s);
		} catch (Exception ex) {
			throw ex;
		}
		finally{
			try {
				reader.close();
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }
    
    public static String readStringFromFile(File file, String encoding) throws IOException{
    	if(!file.exists()) return null;
    	FileInputStream fis = null;
    	InputStreamReader isr = null;
    	StringBuffer sb = new StringBuffer();
    	try {
    		fis = new FileInputStream(file);
    		isr = new InputStreamReader(fis, encoding);
    		int ch = -1;
        	
        	while((ch = isr.read())!=-1) {
        		sb.append((char)ch);
        	} 
    	} finally {
    		if(fis != null) {
    			fis.close();
    			fis = null;
    		}
    		if(isr != null) {
    			isr.close();
    			isr = null;
    		}
    	}    	
    	return sb.toString();
    }
    
    public static String readStringFromFile(File file) throws IOException {
    	return readStringFromFile(file, "GBK");
    }
    
	/**
	 * 重命名文件
	 *
	 * @param fileName
	 * @param name
	 * @return
	 */
	public static boolean rename(String fileName, String name) {
		File file = new File(fileName);
		if (file.getParent() == null) {
			File newFile = new File(name);
			return file.renameTo(newFile);
		} else {
			File newFile = new File(file.getParent(), name);
			return file.renameTo(newFile);
		}
	}

	/**
	 * 移动文件或文件夹
	 * 
	 * @param oldPath
	 * @param newPath
	 * @return
	 */
	public static boolean moveTo(String oldPath, String newPath) {
		File file = new File(oldPath);
		File newFile = new File(newPath);
		if (newFile.exists()) {
			return false;
		} else {
			return file.renameTo(newFile);
		}
	}
	
	/**
	 * 复制文件
	 *
	 * @param src
	 * @param dest
	 * @return
	 */
	public static boolean copyFile(File src, File dest) {
		// 新建文件输入流并对它进行缓冲
		FileInputStream input = null;
		BufferedInputStream inBuff = null;

		// 新建文件输出流并对它进行缓冲
		FileOutputStream output = null;
		BufferedOutputStream outBuff = null;
		try {
			input = new FileInputStream(src);
			inBuff = new BufferedInputStream(input);

			// 新建文件输出流并对它进行缓冲
			output = new FileOutputStream(dest);
			outBuff = new BufferedOutputStream(output);
			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
			return true;
		} catch (Exception e) {
			return false;
		} finally {
			try {
				inBuff.close();
				outBuff.close();
				output.close();
				input.close();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 对文件流进行拷贝
	 *
	 * @param input
	 * @param dest
	 * @return
	 */
	public static boolean copyFile(InputStream input, File dest) {
		// 新建文件输入流并对它进行缓冲
		BufferedInputStream inBuff = null;

		// 新建文件输出流并对它进行缓冲
		FileOutputStream output = null;
		BufferedOutputStream outBuff = null;
		try {
			inBuff = new BufferedInputStream(input);

			// 新建文件输出流并对它进行缓冲
			output = new FileOutputStream(dest);
			outBuff = new BufferedOutputStream(output);
			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
			return true;
		} catch (Exception e) {
			return false;
		} finally {
			try {
				inBuff.close();
				outBuff.close();
				output.close();
				input.close();
			} catch (Exception e) {
			}
		}
	}
	
	/**
	 * 复制单个文件
	 * 
	 * @param oldPathFile
	 *            准备复制的文件源
	 * @param newPathFile
	 *            拷贝到新绝对路径带文件名
	 * @return
	 */
	private static boolean copyFile(String oldPathFile, String newPathFile) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPathFile);
			File newFile = new File(newPathFile);
			if (!newFile.exists()) {
				FileUtil.createFile(newFile);
			}
			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldPathFile); // 读入原文件
				FileOutputStream fs = new FileOutputStream(newPathFile);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 复制整个文件夹的内容
	 * 
	 * @param oldPath
	 *            准备拷贝的目录
	 * @param newPath
	 *            指定绝对路径的新目录
	 * @return
	 */
	private static boolean copyFolder(String oldPath, String newPath) {
		try {
			new File(newPath).mkdirs(); // 如果文件夹不存在 则建立新文件夹
			File a = new File(oldPath);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {
				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file[i]);
				} else {
					temp = new File(oldPath + File.separator + file[i]);
				}
				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
				if (temp.isDirectory()) {// 如果是子文件夹
					copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
				}
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 复制文件或者目录
	 *
	 * @param oldPath
	 * @param newPath
	 * @return
	 */
	public static boolean copy(String oldPath, String newPath) {
		File file = new File(oldPath);
		if (file.isDirectory()) {
			return copyFolder(oldPath, newPath);
		} else {
			return copyFile(oldPath, newPath);
		}
	}

	

	/**
	 * 删除文件或文件夹
	 *
	 * @param filePath
	 * @return
	 */
	public static boolean delele(String filePath) {
		File file = new File(filePath);
		if(!file.exists()){
			return true;
		}
		if (file.isDirectory()) {
			return delFolder(filePath);
		} else {
			return delFile(filePath);
		}
	}

	/**
	 * 删除文件
	 *
	 * @param filePath
	 * @return
	 */
	private static boolean delFile(String filePath) {
		try {
			File myDelFile = new File(filePath);
			myDelFile.delete();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 删除文件夹
	 * 
	 * @param folderPath
	 *            文件夹完整绝对路径
	 * @return
	 */
	private static boolean delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 删除指定文件夹下所有文件
	 * 
	 * @param path
	 *            文件夹完整绝对路径
	 * @return
	 * @return
	 */
	private static boolean delAllFile(String path) {
		boolean bea = false;
		File file = new File(path);
		if (!file.exists()) {
			return bea;
		}
		if (!file.isDirectory()) {
			return bea;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
				bea = true;
			}
		}
		return bea;
	}

	

	/**
	 * 删除文件，可以是单个文件或文件夹
	 * 
	 * @param fileName
	 *            待删除的文件名
	 * @return 文件删除成功返回true,否则返回false
	 */
	public static boolean delete(String fileName) {
		File file = new File(fileName);
		if (!file.exists()) {
			//Log.i(TAG, "delete fail：" + fileName + " no exits!");
			return false;
		} else {
			if (file.isFile()) {
				return deleteFile(fileName);
			} else {
				return deleteDirectory(fileName);
			}
		}
	}

	/**
	 * 删除单个文件
	 * 
	 * @param fileName
	 *            被删除文件的文件名
	 * @return 单个文件删除成功返回true,否则返回false
	 */
	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		if (file.isFile() && file.exists()) {
			file.delete();
			//Log.i(TAG, "delete the file" + fileName + " success!");
			return true;
		} else {
			//Log.i(TAG, "delete the file" + fileName + "fail!");
			return false;
		}
	}

	/**
	 * 删除目录（文件夹）以及目录下的文件
	 * 
	 * @param dir
	 *            被删除目录的文件路径
	 * @return 目录删除成功返回true,否则返回false
	 */
	public static boolean deleteDirectory(String dir) {
		// 如果dir不以文件分隔符结尾，自动添加文件分隔符
		if (!dir.endsWith(File.separator)) {
			dir = dir + File.separator;
		}
		File dirFile = new File(dir);
		// 如果dir对应的文件不存在，或者不是一个目录，则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			//Log.i(TAG, "delete dir fail!" + dirFile + " no exit!");
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag) {
					break;
				}
			}
			// 删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag) {
					break;
				}
			}
		}

		if (!flag) {
			//Log.i(TAG, "delete dir fail!");
			return false;
		}

		// 删除当前目录
		if (dirFile.delete()) {
			//Log.i(TAG, "delete dir" + dir + "success!");
			return true;
		} else {
			//Log.i(TAG, "delete dir" + dir + "fail!");
			return false;
		}
	}


	/**
	 * 删除目录下的文件及目录,不删除目录
	 * 
	 * @param dir
	 *            被删除目录的文件路径
	 * @return 目录删除成功返回true,否则返回false
	 */
	public static boolean deleteFilesUnderDirectory(String dir) {
		// 如果dir不以文件分隔符结尾，自动添加文件分隔符
		if (!dir.endsWith(File.separator)) {
			dir = dir + File.separator;
		}
		File dirFile = new File(dir);
		// 如果dir对应的文件不存在，或者不是一个目录，则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			//Log.i(TAG, "delete dir fail!" + dirFile + " no exit!");
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag) {
					break;
				}
			}
			// 删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag) {
					break;
				}
			}
		}

		if (!flag) {
			//Log.i(TAG, "delete dir fail!");
			return false;
		}
		return true;
	}
	
	/**
	 * 
	* @Title: createFile 
	* @Description: 创建目录和文件
	* @param pathFilename
	*        路径文件名
	* @return     
	*        File
	* @throws
	 */
	public static File createFile(String pathFilename) {
		File file = new File(pathFilename);
		//判断目录是否存在
		if (!file.getParentFile().exists()) {
			if (file.getParentFile().mkdirs()) {
				try {
					boolean ls = file.createNewFile();
					if (!ls) {
						return null;
					}
					return file;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else{//目录创建失败
				return null;
			}
		} else {
			try {
				//删除原先的文件
				if(file.exists()){
					file.delete();
				}
				//创建文件
				boolean ls = file.createNewFile();
				if (!ls) {
					return null;
				}
				return file;
			} catch (IOException e) {
				e.printStackTrace();
				
			}
		}
		return null;
	}
	
		/**
		 * 文件是否存在，如果不存在则创建
		 * @param file
		 * @return
		 * @throws IOException
		 */
		public static final boolean isFileExistOrCreate(File file) throws IOException {
			if(file == null) return false;
			if(file.exists() && file.isFile()) {
				return true;
			}
			if(!file.exists()) {
				File parentFile = file.getParentFile();
				if(parentFile != null && !parentFile.exists()) {
					parentFile.mkdirs();
				}
				return file.createNewFile();
			}
			return false;
		}
}
